package com.youlu.campus.service.douyin;

import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.base.interactive.vo.ActivitySignUpRequest;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.req.CheckMobileVO;
import com.youlu.campus.entity.VO.req.DouYinActivityUserSignUpInfoCommand;
import com.youlu.campus.entity.VO.res.DouYinActivityUserSignUpInfoRes;
import com.youlu.campus.entity.ca.UserCa;
import com.youlu.campus.entity.commission.DistributorChannelActivity;
import com.youlu.campus.entity.dto.sms.SmsBaseInfoDTO;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.activity.UserParticipateActivityInfoService;
import com.youlu.campus.service.ca.UserCaService;
import com.youlu.campus.service.feed.ActivityFeedInfoService;
import com.youlu.campus.service.sms.SmsServerService;
import com.youlu.campus.service.visitor.UserInfoExtendService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class ActivityDouYinService {

    @Lazy
    @Autowired
    private UserParticipateActivityInfoService userParticipateActivityInfoService;

    @Autowired
    private UserInfoExtendService userInfoExtendService;

    @Autowired
    private ActivityFeedInfoService activityFeedInfoService;

    @Lazy
    @Autowired
    private ActivityService activityService;

    @Autowired
    private SmsServerService smsServerService;

    @Autowired
    private UserCaService userCaService;

    @Autowired
    private MongoTemplate mongoTemplate;

    public void updateDouYinActivitySignUp(DouYinActivityUserSignUpInfoCommand command){
        UserPO currentUser = command.getCurrentUser();
        log.info("【更新用户参与活动报名信息】activityId:{},name:{},userId:{}",command.getActivityId(),command.getName(),
                currentUser.getId());

        if (command.getMustCode()) {
            if(StringUtils.isBlank(command.getMobile())){
                throw new BusinessException("手机号必填项");
            }
            SmsBaseInfoDTO dto = SmsBaseInfoDTO.builder().phone(command.getMobile()).code(command.getCode()).build();
            Pair<Boolean, String> re = smsServerService.checkVerifyCode(dto);
            if (!re.getLeft()) {
                throw new BusinessException(re.getRight());
            }
        }
        log.info("【更新用户参与活动报名信息】activityId:{},name:{},userId:{} 基本用户信息",command.getActivityId(),command.getName(),
                currentUser.getId());
        currentUser.setMobile(command.getMobile());
        currentUser.setName(command.getName());
        currentUser.setUniversityId(command.getUniversityId());
        currentUser.setUniversityName(command.getUniversityName());
        currentUser.setAppId(currentUser.getAppId());
        currentUser.setH5SignUp(Boolean.TRUE);
        userInfoExtendService.saveOrUpdate(currentUser);
        log.info("【更新用户参与活动报名信息】activityId:{},name:{},userId:{} 证书用户信息表",command.getActivityId(),command.getName(),
                currentUser.getId());
        UserCa userCa = new UserCa();
        userCa.setUserId(currentUser.getId());
        userCa.setActivityId(command.getActivityId());
        userCa.setName(command.getName());
        userCa.setUniversityId(command.getUniversityId());
        userCa.setUniversityName(command.getUniversityName());
        userCa.setPlatform(currentUser.getCurrentPlatform());
        userCa.setMobile(command.getMobile());
        userCa.setAppId(currentUser.getAppId());
        userCaService.create(userCa);
        log.info("【更新用户参与活动报名信息】activityId:{},name:{},userId:{} 用户参与名单信息表",command.getActivityId(),command.getName(),
                currentUser.getId());
        UserParticipateActivityInfo   userSignUp = new UserParticipateActivityInfo();
        userSignUp.setActivityId(command.getActivityId());
        userSignUp.setUserId(currentUser.getId());
        userSignUp.setUniversityName(command.getUniversityName());
        userSignUp.setUniversityId(command.getUniversityId());
        userSignUp.setMobile(command.getMobile());
        userSignUp.setName(command.getName());
        userSignUp.setNickName(currentUser.getNickName());
        userSignUp.setOpenId(currentUser.getOpenId());
        userSignUp.setAppId(currentUser.getAppId());
        userSignUp.setUnionId(currentUser.getUnionId());
        userSignUp.setAvatarUrl(currentUser.getAvatarUrl());
        userSignUp.setJoined(Boolean.TRUE);
        Date now = new Date();
        Update update = new Update();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(currentUser.getId()));
        query.addCriteria(Criteria.where("activityId").is(command.getActivityId()));
        boolean exists = this.mongoTemplate.exists(query, UserParticipateActivityInfo.class);
        if (!exists) {
           return;
        }
        update.set("updatedTime", now);
        if (StringUtils.isNotBlank(currentUser.getAvatarUrl())) {
            update.set("avatarUrl", currentUser.getAvatarUrl());
        }

        if (StringUtils.isNotBlank(currentUser.getUnionId())) {
            update.set("unionId", currentUser.getUnionId());
        }
        if (StringUtils.isNotBlank(command.getUniversityName())) {
            update.set("universityName", command.getUniversityName());
        }
        if (StringUtils.isNotBlank(command.getUniversityId())) {
            update.set("universityId", command.getUniversityId());
        }
        if (StringUtils.isNotBlank(currentUser.getNickName())) {
            update.set("nickName", currentUser.getNickName());
        }
        if (StringUtils.isNotBlank(command.getName())) {
            update.set("name", command.getName());
        }
        if (StringUtils.isNotBlank(currentUser.getMobile())) {
            update.set("mobile", currentUser.getMobile());
        }
        if (StringUtils.isNotBlank(currentUser.getAppId())) {
            update.set("appId", currentUser.getAppId());
        }
        if (StringUtils.isNotBlank(currentUser.getCurrentPlatform())) {
            update.set("platform", currentUser.getCurrentPlatform());
        }
        if (StringUtils.isNotBlank(currentUser.getOpenId())) {
            update.set("openId", currentUser.getOpenId());
        }
        update.set("joined", Boolean.TRUE);
        FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
        findAndModifyOptions.returnNew(Boolean.TRUE);
        findAndModifyOptions.upsert(Boolean.TRUE);
        this.mongoTemplate.findAndModify(query, update, findAndModifyOptions, UserParticipateActivityInfo.class);
    }

    public DouYinActivityUserSignUpInfoRes getSignUpUserInfo(UserPO currentUser, String activityId){
        String id = currentUser.getId();
        log.info("【抖音活动报名】userId:{},activityId:{}",id,activityId);
        UserInfoExtend userInfoExtend = userInfoExtendService.findByUserId(currentUser.getId());
        DouYinActivityUserSignUpInfoRes userSignUpInfo = new DouYinActivityUserSignUpInfoRes();
        UserParticipateActivityInfo userSignUp = userParticipateActivityInfoService.findByUserIdActivityId(currentUser.getId(), activityId);
        if(Objects.nonNull(userSignUp)){
            userSignUpInfo.setJoined(Boolean.TRUE);
            if(Objects.nonNull(userInfoExtend)){
                userSignUpInfo.setUniversityName(userInfoExtend.getUniversityName());
                userSignUpInfo.setUniversityId(userInfoExtend.getUniversityId());
                userSignUpInfo.setName(userInfoExtend.getName());
                if(StringUtils.isNotBlank(userInfoExtend.getMobile())){
                    userSignUpInfo.setMobile(userInfoExtend.getMobile());
                }
            }
            log.info("【抖音活动报名】userId:{},activityId:{} 已报名",id,activityId);
            return userSignUpInfo;
        }
        log.info("【抖音活动报名】userId:{},activityId:{} 未报名",id,activityId);
        userSignUp = new UserParticipateActivityInfo();
        userSignUp.setActivityId(activityId);
        userSignUp.setUserId(currentUser.getId());
        if(Objects.nonNull(userInfoExtend)){
            userSignUp.setUniversityName(userInfoExtend.getUniversityName());
            userSignUp.setUniversityId(userInfoExtend.getUniversityId());
            userSignUp.setName(userInfoExtend.getName());
            if(StringUtils.isNotBlank(userInfoExtend.getMobile())){
                userSignUp.setMobile(userInfoExtend.getMobile());
            }
        }
        userSignUp.setNickName(currentUser.getNickName());
        userSignUp.setGrade(currentUser.getGrade());
        userSignUp.setJoined(Boolean.TRUE);
        userSignUp.setPassed(Boolean.TRUE);
        userSignUp.setOpenId(currentUser.getOpenId());
        userSignUp.setAppId(currentUser.getAppId());
        userSignUp.setUnionId(currentUser.getUnionId());
        userSignUp.setAvatarUrl(currentUser.getAvatarUrl());
        userParticipateActivityInfoService.saveOrUpdate(userSignUp);
        // 添加Feed流
        ActivityFeedInfo feedInfo = new ActivityFeedInfo();
        feedInfo.setActivityId(activityId);
        feedInfo.setActivityStatus(2);
        feedInfo.setStatus(true);
        feedInfo.setImageUr(currentUser.getAvatarUrl());
        feedInfo.setContent(currentUser.getNickName() + "报名活动");
        activityFeedInfoService.addActivityFeedInfo(activityId, 2, feedInfo);
        activityService.updateActivityJoinNum(activityId, 1, new Date());
        userParticipateActivityInfoService.increJoinedCount(activityId, 1L);
        log.info("【抖音活动报名】userId:{},activityId:{} 报名结束",id,activityId);
        userSignUpInfo.setJoined(Boolean.TRUE);
        return userSignUpInfo;
    }


}
